package com.example.demonstrate.wang.task;

import com.example.demonstrate.wang.annotation.EnableProfilePushTask;
import com.example.demonstrate.wang.constants.Constant;
import com.example.demonstrate.wang.entity.Profile;
import com.example.demonstrate.wang.entity.PushProfileLog;
import com.example.demonstrate.wang.model.StandardProfile;
import com.example.demonstrate.wang.repository.PushProfileLogRepository;
import com.example.demonstrate.wang.service.ProfileSearchService;
import com.example.demonstrate.wang.service.impl.TimeCursorService;
import com.example.demonstrate.wang.utils.DateFormatUtil;
import com.example.demonstrate.wang.utils.ConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author along
 * @Date 2024/6/27 14:47
 */

@Component
@EnableProfilePushTask
@Slf4j
public class AllProfileTask {

    @Autowired
    private ProfileSearchService profileSearchService;

    @Autowired
    private TimeCursorService timeCursorService;

    @Autowired
    private PushProfileLogRepository pushProfileLogRepository;

    @Value("${sync.start.time}")
    private String startTime;

    @Value("${sync.end.time}")
    private String endTime;

    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void wholeProfilePushAsync() {
        log.info("全量档案任务开始");
        // 设置redis时间游标
        timeCursorService.checkAndUpdateTimeCursor(Constant.PROFILE_CURSOR, startTime);
        // 根据游标查询es
        List<Profile> profileLists = profileSearchService.searchProfilesByTime(startTime, endTime, 0, Constant.SEARCH_PER_BATCH_SIZE);
        // 批量消息格式转换
        List<StandardProfile> standardProfiles = ConvertUtil.convertToStandardProfiles(profileLists);
        // 写入文件

        // 写到FTP指定路径

        // mongo中写入日志
        savePushProfileLog(standardProfiles);
        // 更新redis时间游标为最后一条数据的时间戳
        timeCursorService.updateTimeCursor(Constant.PROFILE_CURSOR, DateFormatUtil.format(profileLists.get(profileLists.size() - 1).getCreatedTime()));
    }

    private void savePushProfileLog(List<StandardProfile> standardProfiles) {
        standardProfiles.forEach(standardProfile -> {
            PushProfileLog pushProfileLog = new PushProfileLog();
            BeanUtils.copyProperties(standardProfile, pushProfileLog);
            pushProfileLogRepository.save(pushProfileLog);
        });
    }
}
